// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.account.fragments

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.google.android.material.appbar.CollapsingToolbarLayout
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.account.AccountActivity
import xyz.apiote.bimba.czwek.data.sources.Server
import xyz.apiote.bimba.czwek.repo.User

class AccountFragment : Fragment() {

	companion object {
		fun newInstance() = AccountFragment()
		val LOGOUT_CALLBACK = "bimba://logout".toUri()
	}

	@Suppress("unused")
	private val viewModel: AccountViewModel by viewModels()
	private lateinit var user: User
	private lateinit var _context: Context

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		_context = requireContext()

		user = User.load(_context)
	}

	override fun onResume() {
		super.onResume()
		user = User.load(_context)
		view?.let { setupProfile(it) }
	}

	override fun onCreateView(
		inflater: LayoutInflater, container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		val root = inflater.inflate(R.layout.fragment_account, container, false)

		setupProfile(root)

		root.findViewById<Button>(R.id.edit_profile_button).setOnClickListener {
			startActivity(
				Intent(
					Intent.ACTION_VIEW,
					Server.get(_context).traffic!!.accountEndpoint.toUri()
				)
			)
		}

		root.findViewById<Button>(R.id.logout_button).setOnClickListener {
			val intent = user.logout(_context)
			(activity as AccountActivity).launchLogout(intent)
		}

		return root
	}

	private fun setupProfile(root: View) {
		root.findViewById<CollapsingToolbarLayout>(R.id.collapsing_layout).apply {
			title = _context.getString(R.string.greeting, user.getDisplayName(_context))
			val tf = ResourcesCompat.getFont(_context, R.font.yellowcircle8)
			setCollapsedTitleTypeface(tf)
			setExpandedTitleTypeface(tf)
		}


		MainScope().launch {
			root.findViewById<ImageView>(R.id.avatar).setImageDrawable(user.getAvatar(_context))
		}
		root.findViewById<TextView>(R.id.email).text = user.emailAddress
		root.findViewById<TextView>(R.id.matrix).text = user.matrixID
		root.findViewById<TextView>(R.id.seat).text = user.seat.toString()
		root.findViewById<ImageView>(R.id.email_verified).visibility = if (user.emailVerified) {
			View.VISIBLE
		} else {
			View.GONE
		}
		root.findViewById<ImageView>(R.id.matrix_verified).visibility = if (user.matrixVerified) {
			View.VISIBLE
		} else {
			View.GONE
		}
	}
}